
import { ICapability } from "@/components/capability";
import { asyncConfirm } from "@/tools/fns/asyncConfirm";
import React from "react";
import { v4 as uuidv4 } from 'uuid';
import { MenuController } from "@/controllers/MenuController";

/** 删除菜单 */
export function useDelMenu(record): ICapability {

    const controller = React.useContext(MenuController.Context);

    const onStart = React.useCallback(async () => {
        try {
            await asyncConfirm({ title: '警告！', content: '是否删除菜单' });
            await controller.run(async s => {
                const dl = [record.menuId];
                
                // 获取 record.menuId 的字菜单
                function ct(pid: string) {
                    const children = s.menu.filter(m => m.menuParentId === pid).map(m => m.menuId);
                    dl.push(...children);
                    children.forEach(c => ct(c));
                }
                ct(record.menuId);

                // 删除菜单
                s.menu = s.menu.filter(m => !dl.includes(m.menuId));
            })
        } catch (error) {
            console.error(error);
        }
    }, [controller, record.menuId])

    return {
        id: uuidv4(),
        title: '删除',
        onStart,
    }
}